package net.ib.mtalk.ui.setting.user;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

import net.ib.mntalk.protocol.Common.AccessToken;
import net.ib.mntalk.protocol.Common.AccountAuthToken;
import net.ib.mntalk.protocol.Common.AccountToken;
import net.ib.mntalk.protocol.Session.AcquireAccountAuthTokenRes;
import net.ib.mntalk.protocol.Session.RegisterAccountReq;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.global.GlobalPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;

public class FacebookActivity extends Activity
{
	private Context mContext;
	private FacebookController mUiController;
	
	private static final String FACEBOOK_APP_ID = "122544224495013";
	private static final int FACEBOOK_AUTH_CODE = 32665;

	private Facebook mFacebook = new Facebook(FACEBOOK_APP_ID);
	private ProgressDialog mProgressDialog;
	
	private static final int HANDLER_SHOW_DIALOG = -1;
	private static final int HANDLER_SHOW_ALERTDIALOG = -2;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS:
				Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_SUCCESS", Toast.LENGTH_SHORT).show();
				
				AcquireAccountAuthTokenRes res = (AcquireAccountAuthTokenRes) msg.obj;
				AccountAuthToken accountAuthToken = res.getAccountAuthToken();
				
				mUiController.acquireAccountToServer(accountAuthToken);
				break;
			case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL:
				Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_AUTH_FAIL", Toast.LENGTH_SHORT).show();
				finishActivity();
				break;
			case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_SUCCESS:
				mUiController.setUserAccount((AccountToken)msg.obj);
				break;
			case HandlerMsgConst.HANDLER_ACQUIRE_ACCOUNT_FAIL:
				Toast.makeText(mContext, "HANDLER_ACQUIRE_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
				finishActivity();
				break;
			case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_SUCCESS:
				Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_SUCCESS", Toast.LENGTH_SHORT).show();
				finishActivity();
				break;
			case HandlerMsgConst.HANDLER_REGISTER_ACCOUNT_FAIL:
				Toast.makeText(mContext, "HANDLER_REGISTER_ACCOUNT_FAIL", Toast.LENGTH_SHORT).show();
				finishActivity();
				break;
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				finishActivity();
				break;
			case HANDLER_SHOW_DIALOG:
				mProgressDialog.show();
				break;
			case HANDLER_SHOW_ALERTDIALOG:
				mProgressDialog.hide();
				showAlertDialog(getString(R.string.setting_profile_add_account_exist_msg));
				break;

			default:
				break;
			}
		}
	};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mContext = this;
		
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		
		mUiController = new FacebookController(mContext, mHandler);

		mFacebook.authorize2(this, new String[] {"publish_stream, user_photos, email"}, new AuthorizeListener());
	}
	
	private void showAlertDialog(String msg)
	{
		AlertDialog dialog = new AlertDialog.Builder(mContext).setMessage(msg)
		.setNegativeButton(R.string.ok, new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				finishActivity();
				dialog.dismiss();
			}
		}).create();
		dialog.setCancelable(false);
		dialog.show();
	}
	
	public void finishActivity()
	{
		try {
			mFacebook.logout(mContext);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		mProgressDialog.hide();
		finish();
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		if(mProgressDialog!=null)
			mProgressDialog.dismiss();
	}
	
	//Facebook 인증 후 처리를 위한 callback class
	public class AuthorizeListener implements DialogListener
	{
		public void onCancel() 
		{
			showAlertDialog(getString(R.string.network_error_msg));
		}

		public void onComplete(Bundle values) 
		{
			new AsyncFacebookRunner(mFacebook).request("me", new StreamRequestListener());
			mHandler.sendEmptyMessage(HANDLER_SHOW_DIALOG);
		}

		public void onError(DialogError e) 
		{
			showAlertDialog(getString(R.string.network_error_msg));
		}

		public void onFacebookError(FacebookError e) 
		{
			showAlertDialog(getString(R.string.network_error_msg));
		}
	}
	
	public class StreamRequestListener implements RequestListener 
	{
		public void onComplete(String response, final Object state) 
		{
			try {
				JSONObject obj = Util.parseJson(response);
				if(isExistAccount(obj.getString("email")))
					mHandler.sendEmptyMessage(HANDLER_SHOW_ALERTDIALOG);
				else
					mUiController.acquireAccountAuthToServer(obj.getString("email"), mFacebook.getAccessToken());
			} catch (JSONException e) {
				e.printStackTrace();
			} catch (FacebookError e) {
				e.printStackTrace();
			}
		}
        public void onFacebookError(FacebookError e, final Object state) 
        {
        }

        public void onFileNotFoundException(FileNotFoundException e, final Object state) 
        {
        }

        public void onIOException(IOException e, final Object state) 
        {
        }

        public void onMalformedURLException(MalformedURLException e, final Object state)
        {
        }
    }
	
	private boolean isExistAccount(String account)
	{
		return getIntent().getStringArrayListExtra("facebook").contains(account);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if(FACEBOOK_AUTH_CODE == requestCode)
		{
			mFacebook.authorizeCallback(requestCode, resultCode, data);
		}
	}
}
